let App = getApp();

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		address_id: '',
		name: '',
		region: '',
		phone: '',
		detail: '',
		gender: 0,
	
		options: [{
			city_id: '1',
			city_name: '先生'
		}, {
			city_id: '2',
			city_name: '女士'
		}],
		defaultOption: {
			id: '0',
			name: '称谓'
		}
	},
	onReady() {
		this.select = this.selectComponent("#select")
	},
	/**
	 * 生命周期函数--   监听页面加载
	 */
	onLoad(options) {
		
		this.setData({
			options: options
		})
		let type = options.type
		let that = this
		if (type == 1) {
			wx.setNavigationBarTitle({
				title: '新增收货地址'
			})
		} else {
			that.setData({
				address_id: options.address_id
			})
			wx.setNavigationBarTitle({
				title: '修改收货地址'
			})
			App._get('address/detail', {
				address_id: options.address_id
			}, (result) => {
				let res = result.data.detail
				let defaultOption = (res.gender == 1) ? {
					id: '1',
					name: '先生'
				} : {
					id: '2',
					name: '女士'
				}
				that.setData({
					region: result.data.region,
					name: res.name,
					phone: res.phone,
					detail: res.detail,
					gender: res.gender
				})
				that.select.optionTaps(defaultOption)
			})

		}

	},
	change(e) {
		this.setData({
			gender: e.detail.id
		})
	},
	bindName(e) {
		this.setData({
			name: e.detail.value
		})
	},
	bindDetail(e) {
		this.setData({
			detail: e.detail.value
		})
	},
	bindPhone(e) {
		this.setData({
			phone: e.detail.value
		})
	},
	/**
	 * 表单提交
	 */
	saveData(e) {
		let _this = this
		let info = {
			name: this.data.name,
			phone: this.data.phone,
			region: this.data.region,
			detail: this.data.detail,
			gender: this.data.gender,
			is_copy: 0,
			buy_name: '',
			buy_phone: '',
			buy_gender: ''
		}
		// 表单验证
		if (!_this.validation(info)) {
			App.showError(_this.data.error);
			return false;
		}
		if (_this.data.options.type == 1) {
			// 提交到后端
			App._post_form('address/add', info, function(result) {
				wx.navigateTo({
					url: '/pages/address/index?type=' + _this.data.options.types
				});
			});
		} else {
			info['address_id'] = _this.data.address_id
			// 提交到后端
			App._post_form('address/edit', info, function(result) {
				wx.navigateTo({
					url: '/pages/address/index?type=' + _this.data.options.types
				});
			});
		}
	},

	/**
	 * 表单验证
	 */
	validation(values) {
		if (values.gender == 0) {
			this.data.error = '称谓不能为空';
			return false;
		}
		if (values.name === '') {
			this.data.error = '收件人不能为空';
			return false;
		}
		if (values.phone.length < 1) {
			this.data.error = '手机号不能为空';
			return false;
		}
		let reg = /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/;
		if (!reg.test(values.phone)) {
			this.data.error = '手机号不符合要求';
			return false;
		}
		if (!this.data.region) {
			this.data.error = '省市区不能空';
			return false;
		}
		if (values.detail === '') {
			this.data.error = '详细地址不能为空';
			return false;
		}
		return true;
	},

	/**
	 * 修改地区
	 */
	bindRegionChange(e) {
		this.setData({
			region: e.detail.value
		})
	},


})
